package vip.aster.framework.config;

import jakarta.annotation.Resource;
import jakarta.servlet.Filter;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import vip.aster.common.config.AsterConfig;
import vip.aster.common.filter.repeat.RepeatableFilter;
import vip.aster.framework.demo.DemoInterceptor;
import vip.aster.framework.repeat.RepeatSubmitInterceptor;
import vip.aster.framework.storage.enums.StorageTypeEnum;
import vip.aster.framework.storage.properties.LocalStorageProperties;
import vip.aster.framework.storage.properties.StorageProperties;

/**
 * 通用配置
 *
 * @author Aster
 * @since 2024/1/23 16:52
 */
@Configuration
public class ResourceConfiguration implements WebMvcConfigurer {
    @Resource
    private StorageProperties properties;
    @Resource
    private RepeatSubmitInterceptor repeatSubmitInterceptor;
    @Resource
    private DemoInterceptor demoInterceptor;
    @Resource
    private AsterConfig asterConfig;

    /**
     * 本地资源映射配置
     * @param registry ResourceHandlerRegistry
     */
    @Override
    public void addResourceHandlers(@NotNull ResourceHandlerRegistry registry) {
        // 没开启存储直接返回
        if (!properties.isEnabled()) {
            return;
        }

        // 如果不是本地存储，则返回
        if (properties.getConfig().getType() != StorageTypeEnum.LOCAL) {
            return;
        }

        LocalStorageProperties local = properties.getLocal();
        registry.addResourceHandler("/" + local.getUrl() + "/**")
                .addResourceLocations("file:" + local.getPath() + "/");
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 是否开启演示环境
        if (asterConfig.getDemoEnabled()) {
            // 演示环境拦截器
            registry.addInterceptor(demoInterceptor).addPathPatterns("/**");
        }
        // 防重复提交拦截器
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
    }

    @Bean
    public FilterRegistrationBean<Filter> someFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

}
